package com.example.lte.api;

import com.example.lte.config.LinuxEnvironmentConfig;
import com.example.lte.config.WindowsEnvironmentConfig;
import com.example.lte.constant.SysConst;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

/**
 * @author lzh
 * @date 2020/10/22 - 18:29
 */
@RestController
@Slf4j
@RequestMapping("/pic")
@Api(tags = "图片上传模块")
public class PicUploadController {

    private final WindowsEnvironmentConfig windowsEnvironmentConfig;

    private final LinuxEnvironmentConfig linuxEnvironmentConfig;

    public PicUploadController(WindowsEnvironmentConfig windowsEnvironmentConfig, LinuxEnvironmentConfig linuxEnvironmentConfig) {
        this.windowsEnvironmentConfig = windowsEnvironmentConfig;
        this.linuxEnvironmentConfig = linuxEnvironmentConfig;
    }


    /**
     * http://base64.xpcha.com/pic.html
     * BASE64图片上传--formData形式的参数
     */
    @PostMapping("/uploadBase64JPG")
    public void upload2(String base64) throws IOException {
        String filePath = "";
        Properties props = System.getProperties();
        String os = props.getProperty("os.name");
        if (os.startsWith("Win")) {
            filePath = windowsEnvironmentConfig.getPicUploadDir();
        } else {
            filePath = linuxEnvironmentConfig.getPicUploadDir();
        }

        //  BASE64 方式的 格式和名字需要自己控制（如 png 图片编码后前缀就会是 data:image/png;base64,）
        final File tempFile = new File(filePath+ UUID.randomUUID()+".jpg");
        //  防止有的传了 data:image/png;base64, 有的没传的情况
        String[] d = base64.split("base64,");
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes, tempFile);

    }


    /**
     * MultipartFile 图片上传 限制JPG
     *
     * <form method="post" action="/upload" enctype="multipart/form-data">
     * <input type="file" name="file"><br>
     * <input type="submit" value="提交">
     * </form>
     *
     * @param file MultipartFile
     * @return String
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择图片";
        }
        String fileName = file.getOriginalFilename();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        System.out.println("文件后缀:" + suffix);
        if (!StringUtils.pathEquals(SysConst.IMG_TYPE_JPG, suffix.toUpperCase())) {
            return "上传失败,只允许jpg格式的图片";
        }

        String filePath = "";
        Properties props = System.getProperties();
        String os = props.getProperty("os.name");
        if (os.startsWith("Win")) {
            filePath = windowsEnvironmentConfig.getPicUploadDir();
        } else {
            filePath = linuxEnvironmentConfig.getPicUploadDir();
        }

        File dest = new File(filePath + fileName);
        try {
            //Spring Mvc 提供的写入方式
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败！";
    }

    /**
     * MultipartFile 多图上传
     *
     * <form method="post" action="/multiUpload" enctype="multipart/form-data">
     * <input type="file" name="file"><br>
     * <input type="file" name="file"><br>
     * <input type="file" name="file"><br>
     * <input type="submit" value="提交">
     * </form>
     *
     * @param request HttpServletRequest
     * @return String
     */
    @PostMapping("/multiUpload")
    public String multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "";
        Properties props = System.getProperties();
        String os = props.getProperty("os.name");
        if (os.startsWith("Win")) {
            filePath = windowsEnvironmentConfig.getPicUploadDir();
        } else {
            filePath = linuxEnvironmentConfig.getPicUploadDir();
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "上传第" + (i++) + "个图片失败";
            }
            String fileName = file.getOriginalFilename();

            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                log.info("第" + (i + 1) + "个图片上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "上传第" + (i++) + "个图片失败";
            }
        }

        return "上传成功";

    }


}
